<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./lib/bootstrap.css" />
    <script src="./lib/jquery.js"></script>
  </head>
  <body>
    <!-- 1. 文件选择框 -->
    <input type="file" id="file1" />
    <!-- 2. 上传按钮 -->
    <button id="btnUpload">上传文件</button>
    <div class="progress" style="width: 500px; margin: 15px 15px">
      <div
        class="progress-bar progress-bar-striped active"
        style="width: 0%"
        id="per"
      >
        0%
      </div>
    </div>
    <br />
    <!-- 3. 显示上传到服务器上的图片 -->
    <img src="" alt="" id="img" width="800" />

    <script>
      let btnUpload = document.querySelector("#btnUpload");
      btnUpload.addEventListener("click", function () {
        let files = document.querySelector("#file1").files;
        if (files.length <= 0) return alert("请选择要上传的文件");
        let fd = new FormData();
        fd.append("avatar", files[0]);
        let xhr = new XMLHttpRequest();
        xhr.upload.onprogress = function (e) {
          if (e.lengthComputable) {
            let star = Math.ceil((e.loaded / e.total) * 100);
            $("#per")
              .attr("style", "width:" + star + "%")
              .html(star + "%");
          }
          xhr.upload.onload = function () {
            $("#per")
              .removeClass()
              .addClass("progress-bar progress-bar-success");
          };
        };
        xhr.open("POST", "http://www.liulongbin.top:3006/api/upload/avatar");
        xhr.send(fd);
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            console.log(data);
            if (xhr.status === 200) {
              document.querySelector("#img").src =
                "http://www.liulongbin.top:3006" + data.url;
            } else {
              alert("图片上传失败");
            }
          }
        };
      });
    </script>
  </body>
</html>
